
import os
import re
import subprocess

_out_file = 'mshell_out.txt'
_out_method = None
if not os.path.exists(_out_file):
    open(_out_file,'w').close()

redirected_filter = re.compile(r'.*>[^>]*')

def mshell_do(cmd:str):
    
    try:
        with open(_out_file,'w',encoding='utf-8') as f:
            process = subprocess.Popen(cmd, stdout=f,stderr=f,shell=True,encoding='utf-8')
            output, unused_err = process.communicate()
            retcode = process.poll()
            f.flush()
            if retcode:
                if not _out_file:
                    _out_method('$error\n')
                raise subprocess.CalledProcessError(retcode, cmd, output=output)
        if not _out_file:
            return retcode
        with open(_out_file,'r',encoding='utf-8') as f:
            _out_method(f.read())
        return retcode
    except Exception as e :
        if not _out_method:return None
        _out_method(str(e))
        return None
if __name__=="__main__":
    _out_method = print
    mshell_do("ls")